package info.techgeek.labs.javaSpecialists.curruptObjectState;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BankAccount {
	
	  private  int balance;
	  private final Lock lock = new ReentrantLock();
	  
	  public BankAccount(int balance) {
	    this.balance = balance;
	  }
	  
	  public void deposit(int amount) throws InterruptedException {
		    lock.lockInterruptibly();
		    try {
		      int check = balance + amount;
		      balance = check;
		      if (balance != check) {
		        throw new AssertionError("Data Race Detected");
		      }
		    } finally {
		      lock.unlock();
		    }
		  }
	  
	  public void withdraw(int amount) throws InterruptedException {
	    deposit(-amount);
	  }
  
	  public int getBalance() throws InterruptedException {
		    lock.lockInterruptibly();
		    try {
		      return balance;
		    } finally {
		      lock.unlock();
		    }
		  }
	}
